package com.zjitc.controller;

import com.zjitc.pojo.MyUser;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user/list")
    public String listUsers(@RequestParam(defaultValue = "1")int page,
                            @RequestParam(defaultValue = "3")int pageSize,
                            Model model) {
        int totalCount = userService.getUserCount();
        int totalPages = (int) Math.ceil((double)totalCount / (double)pageSize);

        if (page < 1) page = 1;
        if (pageSize < 1||pageSize > 3) pageSize = 3;

        int offset = (page - 1) * pageSize;

        List<MyUser> users = userService.getUsersByPage(offset, pageSize);

        model.addAttribute("users", users);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "userList";
    }

    @PostMapping("/user/update")
    public String updateUser(MyUser user) {
        userService.updateUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/user/add")
    public String showAddForm() {return "addUser";}

    @PostMapping("/user/add")
    public String addUser(MyUser user) {
        userService.addUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/user/edit/{id}")
    public String showEditForm(@PathVariable int id, Model model) {
            MyUser user = userService.selectUserById(id);
            model.addAttribute("user", user);
            return "editUser";
    }

    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable int id) {
        userService.deleteUser(id);
        return "redirect:/user/list";
    }
}
